<?php

/**
 * 网站更新.
 * 
 * @author aic <41262633@qq.com>
 */

namespace Controller\Admin;

class Update extends \Controller\Admin\Init {

    public function __construct() {
        parent::__construct();
    }

    /**
     * 更新全站文章缓存.
     * 
     * @return void
     */
    public function postitem() {
        $page = $this->getGet('page');
        $page = $page ? $page : 1;

        $limit = 20;

        $totalCount = \Db::instance()->count("select count(`id`) from `post`");

        $totalPage = ceil($totalCount / $limit);
        $nextPage = $page + 1;

        $offset = ($page - 1) * $limit;
        $rows = \Db::instance()->getList("select `post_id`, `title`,`author` from `post` order by `id` desc limit $limit offset $offset");
        foreach ($rows as $r) {
            $itemer = new \Logic\PostItemer($r['post_id'], true);
            $itemer->get();
        }

        $this->assign('page', $page);
        $this->assign('totalPage', $totalPage);
        $this->assign('totalCount', $totalCount);
        $this->assign('nextPage', $nextPage);
        $this->assign('rows', $rows);
        $this->display('admin/update/postitem');
    }

    /**
     * 精选列表更新.
     */
    public function recommend() {
        // 缓存保存目录.
        $cache_dir = CACHE_PATH . 'recommend/';
        if (!file_exists($cache_dir)) {
            mkdir($cache_dir, 0777);
        }

        $limit = 12;

        $tc = \Db::instance()->count("select count(1) from `post` where `status` = '1'");
        $total_page = ceil($tc / $limit);

        // 最多更新五页.
        file_put_contents($cache_dir . 'cache.page.num', $total_page);

        for ($i = 1; $i <= $total_page; $i++) {
            $offset = ($i - 1) * $limit;
            $sql = "select `post_id`,`title`,`author`,`image_url`,`image_uptime`,`long_title` from `post` where `status` = '1'  order by `update_time` desc limit $limit offset $offset";
            $list = \Db::instance()->getList($sql);

            file_put_contents($cache_dir . 'cache.recommend.' . $i, json_encode($list));
        }

        $this->assign('message', '精选列表更新完成');
        $this->display('admin/middle');
    }

}
